package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备Service业务层处理
 *
 * @author mr.du
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 分页查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 同步IOT平台产品列表
     */
    @Override
    public void syncProductList() {
        //1. 调用IOT平台接口查询产品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("查询产品列表失败");
        }

        //2. 将产品列表保存到Redis中
        List<ProductSummary> productList = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(productList));
    }

    /**
     * 查询产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1. 从Redis中查询产品列表JSON字符串
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if (StringUtils.isBlank(productListJSON)) {
            throw new BaseException("产品列表不存在");
        }

        //2. 将JSON字符串解析为产品列表
        List<ProductSummary> productSummaryList = JSONUtil.toList(productListJSON, ProductSummary.class);

        //3. 将每个产品类型转为ProductVo
        List<ProductVo> productVoList = productSummaryList.stream().map(x -> {
            return ProductVo.builder().productName(x.getName()).productKey(x.getProductId()).build();
        }).collect(Collectors.toList());

        //4. 返回数据
        return productVoList;
    }


    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        //1. 判断设备名称是否重复 select count(*) from device where device_name=?
        Long count = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("该设备名称已被注册");
        }
        //2. 判断设备标识是否重复 select count(*) from device where node_id=?
        Long count1 = this.lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count1 > 0) {
            throw new BaseException("该设备已被注册");
        }

        //3. 判断同一位置是否绑定了相同的产品 select count(*) from device where product_key=? and location_type=? and binding_location=?
        Long count2 = this.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .count();
        if (count2 > 0) {
            throw new BaseException("该设备已绑定过同类产品");
        }
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        //4. 调用IOT接口注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();//设备标识码
        body.setNodeId(nodeId);//设备关联的产品ID
        body.setProductId(dto.getProductKey());//设备名称
        body.setDeviceName(dto.getDeviceName());//
        String description = dto.getRegisterDeviceRequest().getNickname();
        body.setDescription(description);//设备描述
        String secret = IdUtil.fastSimpleUUID();
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);//设备秘钥
        request.withBody(body);
        //发起注册设备请求，得到响应结果
        AddDeviceResponse response = client.addDevice(request);
        if (response == null || response.getHttpStatusCode() != 201) {
            throw new BaseException("调用IOT接口注册设备失败");
        }

        //5. 解析响应结果
        String iotId = response.getDeviceId();

        //6. 新增设备到表中
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(iotId);//物联网设备唯一ID
        device.setSecret(secret);//设备密钥
        device.setNodeId(dto.getNodeId());//设备标识符
        device.setDeviceDescription(description);//设备描述
        device.setNickname(description); //设备备注
        String productName = getProductName(dto.getProductKey());
        device.setProductName(productName);//产品名
        boolean result = this.save(device);
        if (!result) {
            throw new BaseException("新增设备失败");
        }
    }

    /**
     * 根据产品ID到Redis中查询产品名称
     *
     * @param productKey
     * @return
     */
    private String getProductName(String productKey) {
        //1. 查询Redis产品列表的JSON字符串
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);

        //2. 解析JSON字符串位产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJSON, ProductSummary.class);

        //3. 筛选出列表中同名产品ID的产品对象
        ProductSummary product = productList.stream().filter(x -> x.getProductId().equals(productKey)).findFirst().get();

        //4. 获取该筛选到的产品对象的产品名
        if (product == null) {
            return null;
        }
        return product.getName();
    }

    @Autowired
    private ISysUserService userService;

    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            throw new BaseException("设备不存在");
        }

        //2.拷贝Device对象为DeviceDedailVo对象
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);

        //3.补充设置一些属性值
        vo.setDeviceSecret(device.getSecret()); //设备密钥
        vo.setGmtCreate(device.getCreateTime());//设备创建时间
        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        vo.setCreator(sysUser.getUserName());//创建人
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());//区域ID

        //4.调用华为云IOT接口获取设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);//设备ID
        ShowDeviceResponse response = client.showDevice(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("调用华为云IOT接口获取设备详情失败");
        }

        //5.补充设置一些属性值

        vo.setDeviceStatus(response.getStatus()); //设备状态：INACTIVE：设备未激活。 ONLINE：设备在线。OFFLINE：设备离线。
        vo.setStatus(response.getStatus());
        //设备激活时间。格式：yyyy-MM-dd'T'HH:mm:ss.SSS'Z' ，如2015-12-12T12:12:122Z。这种时间是国际标准时区的时间，比东八区（亚洲/上海）早8小时
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotBlank(activeTime)) {
            //转换为东八区的时间，且类型为LocalDateTime
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setGmtActive(gmtActive);
        }
        vo.setFirmwareVersion(response.getFwVersion());

        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //1.调用华为云IOT接口查询产品详情
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("调用华为云IOT接口查询产品详情失败");
        }

        //2.解析响应结果
        List<ServiceCapability> serviceCapabilityList = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilityList)){
            throw new BaseException("没有查询到物模型数据");
        }
        ServiceCapability serviceCapability = serviceCapabilityList.get(0);

        //3. 数据类型转换
        JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);

        return jsonObject;
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1. 判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId();//获取设备id

        //2. 调用华为云IOT接口查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response==null || response.getHttpStatusCode()!=200) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据失败");
        }

        //3. 解析响应结果数据，封装map的数据
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        //事件操作时间，格式：yyyyMMdd'T'HHmmss'Z'，如20151212T121212Z。该值是国际标准时间，比东八区早八小时
        String eventTimeStr = reported.getEventTime();//数据上报时间
        //转为东八区时间
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> propertyStatusInfo = new ArrayList<>();
        properties.forEach((k,v)->{
            //封装属性对象
            Map<String,Object> propertyMap = new HashMap<>();
            propertyMap.put("identifier",k);
            propertyMap.put("name",k);
            propertyMap.put("value",v);
            propertyMap.put("time",eventTime);
            propertyStatusInfo.add(propertyMap);
        });

        //4. 返回Map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }
}
